// OrderController.java
package cn.tedu.trading_platform.controller;

import cn.tedu.trading_platform.base.response.JsonResult;
import cn.tedu.trading_platform.base.response.StatusCode;
import cn.tedu.trading_platform.mapper.OrderMapper;
import cn.tedu.trading_platform.pojo.entity.Order;
import cn.tedu.trading_platform.pojo.vo.OrderVO;
import cn.tedu.trading_platform.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/orders/")
@Api(tags = "订单管理模块")
public class OrderController {
    @Autowired
    private OrderMapper orderMapper;

    @PostMapping("create")
    @ApiOperation("创建订单")
    public JsonResult createOrder(@Validated @RequestBody Order order, HttpSession session) {
        log.debug("开始处理创建订单请求");
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.USER_NOT_LOGIN);
        }
        order.setUserId(userVO.getId());
        order.setStatus(1); // 默认状态为待支付
        orderMapper.insertOrder(order);
        return JsonResult.ok(order.getId()); // 返回订单ID
    }

    @PostMapping("delete/{id}")
    @ApiOperation("删除订单")
    public JsonResult deleteOrder(@PathVariable Long id, HttpSession session) {
        log.debug("开始处理删除订单请求");
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.USER_NOT_LOGIN);
        }
        int rows = orderMapper.deleteOrder(id);
        return rows > 0 ? JsonResult.ok() : new JsonResult(StatusCode.OPERATION_FAIL);
    }

    @GetMapping("list")
    @ApiOperation("查询用户订单列表")
    public JsonResult listOrders(HttpSession session) {
        log.debug("开始处理查询订单请求");
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.USER_NOT_LOGIN);
        }
        List<OrderVO> orders = orderMapper.selectOrdersByUserId(userVO.getId());
        return JsonResult.ok(orders);
    }

    @PostMapping("updateStatus")
    @ApiOperation("更新订单状态")
    public JsonResult updateStatus(
            @PathVariable Long id,
            @RequestParam Integer status,
            HttpSession session) {
        log.debug("开始处理更新订单状态请求");
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(StatusCode.USER_NOT_LOGIN);
        }
        int rows = orderMapper.updateOrderStatus(id, status);
        return rows > 0 ? JsonResult.ok() : new JsonResult(StatusCode.OPERATION_FAIL);
    }
}
